import Vue from 'vue'
import request from '@/utils/api/request'

let previousController

export class Store {
  constructor(data = []) {
    this.view = Vue.observable({
      data,
      page: 1,
      pageSize: 10,
      total: 0,
      status: 0,
      loading: false
    })
  }

  async loadData(params) {
    if (previousController) {
      // 取消上一个请求 重新开始一个请求
      previousController.abort()
    }
    const controller = new AbortController()
    previousController = controller
    const signal = controller.signal

    this.status = 1
    this.loading = true

    try {
      const { data } = await request.get(this.url, {
        ...params,
        signal
      })

      if (data.status === 200) {
        this.status = 2
        this.loading = false
        this.data = data.data.data
        this.page = data.data.page
        this.pageSize = data.data.pageSize
        this.total = data.data.total
      }
    } catch (error) {
      // 需要提供空数据让重试按钮显示
      this.data = []
      this.status = 3
      this.loading = false
    }
  }

  get data() {
    return this.view.data
  }
  set data(newVal) {
    this.view.data = newVal
  }
  get page() {
    return this.view.page
  }
  set page(newVal) {
    this.view.page = newVal
  }
  get pageSize() {
    return this.view.pageSize
  }
  set pageSize(newVal) {
    this.view.pageSize = newVal
  }
  get total() {
    return this.view.total
  }
  set total(newVal) {
    this.view.total = newVal
  }
  get status() {
    return this.view.status
  }
  set status(newVal) {
    this.view.status = newVal
  }
  get loading() {
    return this.view.loading
  }
  set loading(newVal) {
    this.view.loading = newVal
  }
}

export class Model {
  constructor(data = {}) {
    this.view = Vue.observable({
      data
    })
  }

  // 查指定数据
  async findData(id) {
    this.status = 1
    this.loading = true
    try {
      const { data } = await request.get(this.proxy.action.findDataUrl)
      if (data.status === 200) {
        this.status = 2
        this.data = data.data
      }
    } catch (e) {
      this.status = 3
      console.log(e)
    }
  }
  // 新增数据
  async editorData(params) {
    this.status = 1
    this.loading = true
    try {
      const { data } = await request.get(this.proxy.action.findDataUrl, { params })
      if (data.status === 200) {
        this.status = 2
        this.data = data.data
      }
    } catch (e) {
      this.status = 3
      console.log(e)
    }
  }

  get data() {
    return this.view.data
  }
  set data(newVal) {
    this.view.data = newVal
  }
}
